package com.dkd.manage.service.Impl;

import com.dkd.manage.constant.MessageConstant;
import com.dkd.manage.exception.DeleteException;
import com.dkd.manage.mapper.NodeMapper;
import com.dkd.manage.mapper.VmMapper;
import com.dkd.manage.pojo.dto.NodeQueryListDto;
import com.dkd.manage.pojo.dto.VmQueryListDto;
import com.dkd.manage.pojo.entity.Node;
import com.dkd.manage.pojo.vo.NodeVo;
import com.dkd.manage.pojo.vo.VendingMachineVo;
import com.dkd.manage.result.PageResult;
import com.dkd.manage.service.NodeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class NodeServiceImpl implements NodeService {


    @Autowired
    private NodeMapper nodeMapper;
    @Autowired
    private VmMapper vmMapper;

    /**
     * 分页查询点位列表
     * @param nodeQueryListDto
     * @return
     */
    @Override
    public PageResult<NodeVo> list(NodeQueryListDto nodeQueryListDto) {
        //开启分页
        PageHelper.startPage(nodeQueryListDto.getPageNum(), nodeQueryListDto.getPageSize());
        //查询点位列表
        List<NodeVo> nodeVoList =  nodeMapper.list(nodeQueryListDto);
        //获取分页详情对象
        PageInfo<NodeVo> pageInfo = new PageInfo<NodeVo>(nodeVoList);
        //封装数据返回
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }


    /**
     * 新增点位
     * @param node
     * @return
     */
    @Override
    public Integer add(Node node) {
        return nodeMapper.add(node);
    }

    /**
     * 根据id查询点位
     * @param id
     * @return
     */
    @Override
    public Node getNodeById(Long id) {
        return nodeMapper.getNodeById(id);
    }

    /**
     * 修改点位
     * @param node
     * @return
     */
    @Override
    public Integer edit(Node node) {
        return nodeMapper.edit(node);
    }

    /**
     * 根据id删除点位
     * @param ids
     * @return
     */
    @Override
    public Integer deleteNodeById(Long[] ids) {
        VmQueryListDto vmQueryListDto = VmQueryListDto.builder()
                .pageNum(1)
                .pageSize(10)
                .build();
        //循环遍历要删除的点位，判断其是否关联了设备
        for (Long id : ids) {
            vmQueryListDto.setNodeId(id);
            List<VendingMachineVo> list = vmMapper.list(vmQueryListDto);
            if(list != null && list.size() > 0) {
                throw new DeleteException(MessageConstant.NODE_NOT_DELETE);
            }
        }
        return nodeMapper.deleteNodeById(ids);
    }
}
